<?php

namespace App\Console\Commands;

use App\Http\Models\ZtkGoods;
use App\Http\Models\ZtkTask;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class getGoodsDetial extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'getGoodsDetial';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新商品销量等数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //3510之前的老数据忽略
        $data = ZtkTask::where('id','>',3510)->whereIn('status',[1,2,3])->get();
        foreach($data as $k=>$v)
        {
            try {
                $model = ZtkGoods::where('task_id',$v->id)->first();
                if(empty($model)) continue;

                $url = 'http://zsqapi.52tbc.com/v1/ext/parseClip';
                $data = [
                    'content' => $v->content
                ];
                $res = $this->postCurl($url,$data);

                $model->good_thirty_amount = $res['data']['good_thirty_amount']; //月销
                $model->coupon_use = $res['data']['coupon_use']; //已领取
                $model->good_sales = $res['data']['good_sales']; //销量
                $model->save();

            } catch (\Exception $e) {
                continue;
            }
        }
    }

    public function postCurl($url = '', $data = '')
    {
        $data = http_build_query($data);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/x-www-form-urlencoded"
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        $response = json_decode($response,1);
        return $response;
    }
}
